package org.fjsei.yewu.config;

import io.minio.MinioClient;
import okhttp3.OkHttpClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    // 新增配置属性：是否忽略SSL验证
    private boolean ignoreSslVerification = false;

    @Bean
    public MinioClient minioClient() throws NoSuchAlgorithmException, KeyManagementException {
        MinioClient.Builder builder = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey);

        // 只有当配置为忽略SSL验证时才创建自定义HTTP客户端
        if (ignoreSslVerification) {
            // 创建信任所有证书的SSL上下文
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // 配置OkHttpClient以忽略SSL验证
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            httpClientBuilder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            httpClientBuilder.hostnameVerifier((hostname, session) -> true); // 忽略主机名验证

            builder.httpClient(httpClientBuilder.build());
        }

        return builder.build();
    }
}


/*【验证minIO过期文件的清理】终于可以了。
ywmast桶首页：
    Object Locking: 有；  Versioning=Versioned；  Quota:Enabled 4MB;  Replication:Disabled;
    Retention: Enabled Mode:Compliance  Validity:99 Years;
桶主页->Lifecycle Rules子页面的>> 配置的2条规则：
规则1的 类别 Expiry
    Non-Current
    非当前超期时间= 1 days
    Enabled 这一条点击进入 高级的  Object Delete Marker开关==OFF;
    过滤器为空的
规则2的  类别 Expiry
    Tier prefix都是为空的；
    Current Version ；
    Expiry Daya超期天数配置=11 。
    这两条页面增加的规则。
* */
